package cn.itcast.smsservice.service.impl;

import cn.itcast.smsservice.service.SmsService;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
public class SmsServiceImpl implements SmsService {
    @Override
    public boolean send(Map<String, Object> params, String phone) {
        if(StringUtils.isEmpty(phone)) return false;

        DefaultProfile profile = DefaultProfile.getProfile("default","LTAI4G8fKqEgygE1WzHsiVDm","AR2ppon4fdsi7c7H67CSoax60NJHpe");
        IAcsClient client = new DefaultAcsClient(profile);

        // 设置相关固定的参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        // 设置发送相关的参数
        request.putQueryParameter("PhoneNumbers",phone); // 手机号
        request.putQueryParameter("SignName","蘑菇在线"); // 申请阿里云 签名名称
        request.putQueryParameter("TemplateCode","SMS_192820771"); // 申请阿里云 模板code
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(params)); //验证码数据，转换json数据传递

        try {
            // 最终发送
            CommonResponse response = client.getCommonResponse(request);

            boolean success = response.getHttpResponse().isSuccess();

            return success;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
